﻿using System.Text.RegularExpressions;
using BoldBrick.Core.Logging;
using Microsoft.SharePoint;

namespace BoldBrick.SharePoint.CommonControls.Extensions
{
	/// <summary>
	/// Extension class for <see cref="string"/> objects
	/// </summary>
	public static class StringEx
	{
		private static readonly ILogger log = Logger.GetLogger(typeof (StringEx));

		/// <summary>
		/// Replaces all place holders with values from list item
		/// </summary>
		/// <param name="source">Source text with place holders</param>
		/// <param name="listItem">List item with values</param>
		/// <returns>Returns text with replaced place holders</returns>
		public static string ReplacePlaceHolders(this string source, SPListItem listItem)
		{
			const string placeHolderPattern = @"{{(.*?)}}";
			MatchCollection matchCollection = Regex.Matches(source, placeHolderPattern, RegexOptions.Singleline);

			foreach (Match match in matchCollection)
			{
				string fieldName = match.Groups[1].Value;
				SPField field = listItem.Fields.TryGetFieldByStaticName(fieldName);
				if (field == null)
				{
					log.Write(LogLevel.Warn, "'{0}' field not found in '{0}' item.", fieldName, listItem.Url);
					continue;
				}

				string placeHolder = match.Value;
				object value = listItem[fieldName];

				string valueText = GetValueText(field, value);
				
				source = source.Replace(placeHolder, valueText);
			}

			return source;
		}

		/// <summary>
		/// Gets text represenation of the value
		/// </summary>
		/// <param name="field">Field of the value</param>
		/// <param name="value">The value</param>
		/// <returns>Returns text represenation of the value</returns>
		private static string GetValueText(SPField field, object value)
		{
			if (value == null)
				return string.Empty;

			// look up field
			if (field  is SPFieldLookup)
			{
				SPFieldLookupValue fieldValue = field.GetFieldValue(value.ToString()) as SPFieldLookupValue;
				if (fieldValue != null)
				{
					return fieldValue.LookupValue;
				}
			}

			return value.ToString();
		}
	}
}
